import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { getMenuList, setMenuData } from "@/api/menu";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

export function useMenu() {
  const form = reactive({
    title: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const getMenuType = (type, text = false) => {
    switch (type) {
      case "menu":
        return text ? "菜单" : "primary";
      case "iframe":
        return text ? "iframe" : "warning";
      case "link":
        return text ? "外链" : "danger";
      default:
        return text ? "按钮" : "info";
    }
  };

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "menu_name",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{transformI18n(row.menu_name)}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "menu_type",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getMenuType(row.menu_type)}
          effect="light"
        >
          {getMenuType(row.menu_type, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "route_path"
    },
    {
      label: "组件路径",
      prop: "component_path",
      formatter: ({ route_path, component_path }) =>
        isAllEmpty(component_path) ? route_path : component_path
    },
    {
      label: "权限标识",
      prop: "permission_code"
    },
    {
      label: "排序",
      prop: "rank",
      width: 100
    },
    {
      label: "隐藏",
      prop: "show_link",
      formatter: ({ showLink }) => (showLink ? "否" : "是"),
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      align: "left",
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getMenuList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    dataList.value = handleTree(data, "id", "pid"); // 处理成树结构
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function formatHigherMenuOptions(treeList, isShowTop = true) {
    const newTreeList = [];
    if (isShowTop) {
      newTreeList.push({
        menu_name: "顶级菜单",
        pid: 0,
        id: 0
      });
    }

    if (!treeList || !treeList.length) return newTreeList;
    for (let i = 0; i < treeList.length; i++) {
      // 过滤掉按钮类型
      if (treeList[i].menu_type == "btn") continue;
      treeList[i].title = transformI18n(treeList[i].title);
      treeList[i].children = formatHigherMenuOptions(
        treeList[i].children,
        false
      );
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          menu_type: row?.menu_type ?? "menu",
          higherMenuOptions: formatHigherMenuOptions(cloneDeep(dataList.value)),
          pid: row?.pid ?? 0,
          menu_name: row?.menu_name ?? "",
          route_name: row?.route_name ?? "",
          route_path: row?.route_path ?? "",
          component_path: row?.component_path ?? "",
          rank: row?.rank ?? 99,
          redirect_url: row?.redirect_url ?? "",
          icon: row?.icon ?? "",
          extra_icon: row?.extra_icon ?? "",
          enter_transition: row?.enter_transition ?? "",
          leave_transition: row?.leave_transition ?? "",
          active_path: row?.active_path ?? "",
          permission_code: row?.permission_code ?? "",
          frame_src: row?.frame_src ?? "",
          frame_loading: row?.frame_loading ?? true,
          is_keep_alive: row?.is_keep_alive ?? false,
          is_hide: row?.is_hide ?? false,
          is_affix: row?.is_affix ?? false,
          show_link: row?.show_link ?? true,
          show_parent: row?.show_parent ?? false
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        // 删除curData中的higherMenuOptions
        delete curData.higherMenuOptions;
        function chores() {
          setMenuData(curData).then(response => {
            message(response.message, {
              type: response.code == 1 ? "success" : "error"
            });
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            chores();
          }
        });
      }
    });
  }

  function handleDelete(row) {
    message(`您删除了菜单名称为${transformI18n(row.menu_name)}的这条数据`, {
      type: "success"
    });
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange
  };
}
